import { Router } from 'express';
import { AuthMiddleware } from '../../../core/middleware/auth.js';
import { AdminUserController } from './controller.js';
import { errorHandler } from './../../../core/middleware/errorHandler.js';
import { 
  getUserListSchema,batchDeleteUsersSchema,
  createUserSchema,
  updateUserSchema,
  resetPasswordSchema
} from './schema.js';
import { API_URLS } from "../../../config/api-urls.js";

const router = Router();
const  ADMIN_ROLES=['admin',"superadmin"]

// 管理员权限检查中间件
const requireAdmin = AuthMiddleware.authorize(ADMIN_ROLES);

router.get("/test", (req, res) => res.send("Test route works"));

// 用户列表
router.get(
   API_URLS.GET_USER_LIST,
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  requireAdmin,
  AuthMiddleware.validate(getUserListSchema),
  AdminUserController.getUsersList
);

// 创建用户
router.post(
  API_URLS.CREATE_USER,
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  requireAdmin,
  AuthMiddleware.validate(createUserSchema),
  AdminUserController.createUser
);
// 获取当前用户信息 (需要认证)
router.get(
  API_URLS.GET_CURRENT_USER,
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  AuthMiddleware.authorize(ADMIN_ROLES), // 仅限管理员
  (req, res,err) => AdminUserController.getCurrentUser(req, res,err) // 直接透传req/res
);
// 用户详情
router.get(
  API_URLS.GET_USER_INFO,
  AuthMiddleware.authenticate(process.env.JWT_SECRET),  // --身份认证
 (req, res,err) => {
    // 直接使用Token中的用户ID
    AdminUserController.getUserInfo(req, res  ,err);
  }
);
// 管理员获取特定用户信息（需显式传ID）
router.get(
  API_URLS.GET_USER_DETAIL,
  AuthMiddleware.authenticate(process.env.JWT_SECRET),  // --身份认证
  requireAdmin,  // --管理员权限校验
  AdminUserController.getUserInfo  // --获取用户数据
);
// 更新用户
router.put(
  API_URLS.UPDATE_USER,
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  requireAdmin,
  AuthMiddleware.validate(updateUserSchema),
  AdminUserController.updateUser
);

// 重置密码
router.post(
  '/:id/reset-password',
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  requireAdmin,
  AuthMiddleware.validate(resetPasswordSchema),
  AdminUserController.resetPassword
);

// 删除用户
router.delete(
  '/:id',
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  requireAdmin,
  AdminUserController.deleteUser
);
// 批量删除用户
router.post(
  API_URLS.BATCH_DELETE_USERS,
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  requireAdmin,
  AuthMiddleware.validatePure(batchDeleteUsersSchema), // 3. 纯数据验证
  AdminUserController.batchDeleteUsers
);

// 恢复用户
router.post(
  '/:id/restore',
  AuthMiddleware.authenticate(process.env.JWT_SECRET),
  requireAdmin,
  AdminUserController.restoreUser
);

// 在所有路由之后添加错误处理中间件
router.use(errorHandler);

export default router;